package com.zzyl.service.impl;

import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import io.swagger.util.Json;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

public class WechatServiceimpl implements WechatService  {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.framework.wechat.appId}")
    private String appid;

    @Value("${zzyl.framework.wechat.appSecret}")
    private String secret;
    @Override
    public String getOpenid(String code) {

        Map<String,Object> paramMap=getAppConfig();
        paramMap.put("js_code",code);

        HttpRequest request = HttpUtil.createRequest(Method.GET, REQUEST_URL);
        JSONObject jsonObject = JSONUtil.parseObj(request);

        //判断响应是否出错
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("openid"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        String openid = jsonObject.getStr("openid");

        return openid;
    }



    @Override
    public String getPhone(String datailCode) {
        return "";
    }

    /**
     * 封装公共参数
     * @return
     */
    private Map<String, Object> getAppConfig() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        return paramMap;
    }
}
